<?php
/**
 * Created by PhpStorm.
 * User: Janpoem
 * Date: 2016/2/1 0001
 * Time: 17:01
 */

namespace CSService\Helper;


class CSCipher
{

	private $encryptKey = '';

	private $blocksize = 16;

	public static function makeRandKey($length = 16)
	{
		$keys = '';
		for ($i = 0; $i < $length; $i++) {
			$keys .= chr(mt_rand(33, 126));
		}
		return $keys;
	}

	public function __construct($key)
	{
		$key = trim($key);
		if (empty($key))
			throw new \Exception("Invalid encrypt key!");
		$this->encryptKey = md5($key, true);
	}

	public function decode($data)
	{
		return hex2bin($data);
//		return base64_decode($data);
	}

	public function encode($data)
	{
		return bin2hex($data);
//		return base64_encode($data);
	}

	public function decrypt($data)
	{
		$decode = $this->decode($data);
		$hash = substr($decode, -16);
		$ivContent = substr($decode, 0, -16);
		if (md5($ivContent, true) !== $hash)
			return false;
		$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
		$iv = substr($ivContent, 0, $ivSize);
		$content = substr($ivContent, $ivSize);
		$decrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->encryptKey, $content, MCRYPT_MODE_CBC, $iv);
		return $decrypt;
	}

	public function encrypt($data)
	{
		$pad = $this->blocksize - (strlen($data) % $this->blocksize);
		$data = $data . str_repeat(chr($pad), $pad);
		///
		$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
		$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
		$cipherContent = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->encryptKey, $data, MCRYPT_MODE_CBC, $iv);
		$result = $iv . $cipherContent;
		$hash = md5($result, true);
		$result = $result . $hash;
		////
		return $this->encode($result);
	}
}